package ioc

import (
	grpc2 "gitee.com/xiao_hange/go-admin-file/file/grpc"
	"gitee.com/xiao_hange/go-admin-file/file/ioc/config"
	"gitee.com/xiao_hange/go-admin-pkg/pkg/grpcx"
	gRPClogger "gitee.com/xiao_hange/go-admin-pkg/pkg/grpcx/interceptors/log"
	gRPCratelimit "gitee.com/xiao_hange/go-admin-pkg/pkg/grpcx/interceptors/ratelimit"
	"gitee.com/xiao_hange/go-admin-pkg/pkg/grpcx/interceptors/trace"
	"gitee.com/xiao_hange/go-admin-pkg/pkg/logger"
	"gitee.com/xiao_hange/go-admin-pkg/pkg/ratelimit"
	"github.com/redis/go-redis/v9"
	"google.golang.org/grpc"
	"time"
)

// 注意 InitGrpcServer(filev1 *grpc2.FileServiceServer) 要使用指针  要和 NewInitGrpcServer 返回保持一样

func InitGrpcServer(filev1 *grpc2.FileServiceServer, l logger.GrpcLogger, client redis.Cmdable, cfg *config.ServerConfig, ja *config.JaegerConfig) *grpcx.Server {
	tracerProvider := InitOTELTracerProvider(ja)
	otelBuilder := trace.NewOTELInterceptorBuilder("file-grpc-server", tracerProvider.Tracer("file-grpc-server"), nil)

	server := grpc.NewServer(
		grpc.ChainUnaryInterceptor(
			otelBuilder.BuildUnaryServerInterceptor(),
			gRPClogger.NewLoggerInterceptorBuilder(l).BuildUnaryServerInterceptor(),
			gRPCratelimit.NewInterceptorBuilder(ratelimit.NewRedisSlideWindowLimiter(client, time.Second, 100), "grpc").BuildServerInterceptor(),
			//gRPCratelimit.NewInterceptorBuilder(ratelimit.NewRedisSlideWindowLimiter(client, time.Minute, 6), "grpc").BuildServerInterceptor(),
		),
	)
	filev1.Register(server)
	return &grpcx.Server{
		Server:      server,
		Port:        cfg.Port,
		EtcdAddrs:   []string{cfg.EtcdAddr},
		Name:        "file",
		L:           l,
		ConsulAddrs: cfg.ConsulAddr,
		Weight:      cfg.Weight,
		Label:       cfg.Label,
		ServerName:  "File",
		//IpOrServerName: cfg.ServerName,
	}
}
